/*
 * Copyright (C) 2008  Young,Fey <fey.young@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */ 
package com.youngfey.wordmaster.database.tables

import com.youngfey.database.annotation.*
import com.youngfey.wordmaster.database.*
import static com.youngfey.wordmaster.database.Database.*

@Unique(['ARTICLE, PROPERTY, VALUE'])
public class PropertyIndex {
    Article article
    Property property
    String value

    // <editor-fold defaultstate="collapsed" desc=" Generated Code (by gRDB)">
    Integer id
    

    boolean equals(Object o) {
        id != null && o instanceof PropertyIndex && id == o.getId()
    }

    static createTable() {
        execute("CREATE TABLE PropertyIndex (Id INT NOT NULL GENERATED ALWAYS AS IDENTITY CONSTRAINT PROPERTYINDEX_PK PRIMARY KEY, Article INT NOT NULL, Property INT NOT NULL, Value VARCHAR(255) NOT NULL)")
        
        execute('CREATE UNIQUE INDEX UIX_ARTICLE_PROPERTY_VALUE__PROPERTYINDEX ON PropertyIndex (ARTICLE, PROPERTY, VALUE)')
        
    }

    boolean isValid() {
        article != null && property != null && value?.size() <= 255
    }


    boolean isConflicted() {
    
        def idUIX_ARTICLE_PROPERTY_VALUE = findIdByUIX_ARTICLE_PROPERTY_VALUE(aRTICLE, pROPERTY, vALUE)
        if(idUIX_ARTICLE_PROPERTY_VALUE != null && idUIX_ARTICLE_PROPERTY_VALUE != id) return true
    
        false
    }

    
    Integer findIdByUIX_ARTICLE_PROPERTY_VALUE(aRTICLE, pROPERTY, vALUE) {
        firstRow("SELECT ID FROM PropertyIndex WHERE ARTICLE = $aRTICLE AND PROPERTY = $pROPERTY AND VALUE = $vALUE")?.id
    }
    


    static PropertyIndex create(article, property, value) {
        def instance = new PropertyIndex(article: article, property: property, value: value)
        instance.insert()
        instance
    }

    def insert() {
        if(id == null && isValid()) {
            id = executeInsert("INSERT INTO PropertyIndex (Article, Property, Value) VALUES (${article?.getId()}, ${property?.getId()}, ${value})")[0][0]
            if(id != null) {
                
                return
            }
        }

        throw new IllegalStateException()
    }

    //capitalize;
    static PropertyIndex find(Integer id) {
        if(id == null) return null

        

        def row = firstRow("SELECT * FROM PropertyIndex WHERE Id = $id")
        
        row ? new PropertyIndex(id: row.Id, article: Article.find((Short)row.article), property: Property.find((Short)row.property), value: row.value) : null
        
    }

    static ArrayList<PropertyIndex> findBySql(stmt) {
        def rows = []
        eachRow(stmt) {row ->
            rows << new PropertyIndex(id: row.Id, article: Article.find((Short)row.article), property: Property.find((Short)row.property), value: row.value)
        }
        
        rows
    }

    static ArrayList<PropertyIndex> findAll() {
        findBySql('SELECT * FROM PropertyIndex')
    }

    
    static ArrayList<PropertyIndex> findAll(String keyword) {
        findBySql("SELECT * FROM PropertyIndex WHERE (Value LIKE $keyword)")
    }
    

    private executeUpdate(stmt) {
        def updated = executeUpdate(stmt)
        if(updated != 1) throw new IllegalStateException()
        
    }

    def update() {
        if(id != null && isValid()) {
            executeUpdate("UPDATE PropertyIndex SET Article = ${article?.getId()}, Property = ${property?.getId()}, Value = ${value} WHERE Id = $id")
        }
    }

    static delete(Integer id) {
        execute("DELETE FROM PropertyIndex WHERE Id = $id")
        
    }

    def delete() {
        if(id != null) delete(id)
    }


    static ArrayList<PropertyIndex> findByArticle(value) {
        findBySql("SELECT * FROM PropertyIndex WHERE Article = ${value?.getId()}")
    }

    static ArrayList<PropertyIndex> findByProperty(value) {
        findBySql("SELECT * FROM PropertyIndex WHERE Property = ${value?.getId()}")
    }

    static ArrayList<PropertyIndex> findByValue(value) {
        findBySql("SELECT * FROM PropertyIndex WHERE Value = ${value}")
    }



    static ArrayList<PropertyIndex> findByArticleLike(String keyword) {
        findBySql("SELECT * FROM PropertyIndex WHERE Article LIKE $keyword")
    }

    static ArrayList<PropertyIndex> findByPropertyLike(String keyword) {
        findBySql("SELECT * FROM PropertyIndex WHERE Property LIKE $keyword")
    }

    static ArrayList<PropertyIndex> findByValueLike(String keyword) {
        findBySql("SELECT * FROM PropertyIndex WHERE Value LIKE $keyword")
    }



    def updateArticle(value) {
        this.article = value

        if(id != null && isValid()) {
            executeUpdate("UPDATE PropertyIndex SET Article = ${value?.getId()} WHERE Id = $id")
        } else {
            throw new IllegalStateException("Update Error: value = $value")
        }
    }

    def updateProperty(value) {
        this.property = value

        if(id != null && isValid()) {
            executeUpdate("UPDATE PropertyIndex SET Property = ${value?.getId()} WHERE Id = $id")
        } else {
            throw new IllegalStateException("Update Error: value = $value")
        }
    }

    def updateValue(value) {
        this.value = value

        if(id != null && isValid()) {
            executeUpdate("UPDATE PropertyIndex SET Value = ${value} WHERE Id = $id")
        } else {
            throw new IllegalStateException("Update Error: value = $value")
        }
    }



    // </editor-fold>
}
